#include "stdio.h"
#include "stdlib.h"

static char zeros[16];

/*
	the actual linked image goes to 0x7e80.  the next 128 bytes are
	reserved for tags, which are RW by OFW, and RO by the EC.
	those bytes will be 0 in the image file, but skipped when
	writing by OFW.  our version string goes at 0x7f00.  the
	last 16 bytes starting at 0x7ff0 consist of two bytes of
	actual linked image length (i.e. 80, 7e), a couple of zeros,
	a primitive checksum and xor byte, and 6 more zero bytes.
	the last 4 bytes are an overall file checksum, used for
	file verification by OFW.
 */

main(int argc, char *argv[])
{
	int c;
	unsigned char sum = 0;
	unsigned char xor = 0;
	unsigned short len = 0;
	unsigned char b;
	unsigned int eoi = 0;

	if (argc != 2)
	{
		fprintf(stderr, "usage: sum_3731 0xend-of-image\n");
		exit(1);
	}

	eoi = strtol(argv[1], 0, 16);
	if (!eoi)
	{
		fprintf(stderr, "sum_3731: bad end-of-image\n");
		exit(1);
	}

	while (1)
	{
		c = getchar();
		if (c < 0) break;
		sum += c;
		sum &=0xff;
		xor ^= c;
		len += 1;
		putchar(c);
		if (len >= eoi) break;
	}
	while (1)
	{
		c = getchar();
		if (c < 0) break;
		len += 1;
		putchar(c);
		if (len >= 0x7ff0) break;
	}
	fprintf(stderr, "3731 image len is 0x%x, sum is 0x%x, xor is 0x%x\n",
			eoi, sum, xor);

	fflush(stdout);

	b = eoi & 0xff;
	write(1, &b, 1);

	b = (eoi >> 8) & 0xff;
	write(1, &b, 1);

	write(1, zeros, 2);

	write(1, &sum, 1);
	write(1, &xor, 1);

	write(1, zeros, 6);

	return 0;
}

